﻿using PageAdmin.Utils.ORM;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace PageAdmin.Utils.BLL
{
    /// <summary>
    /// 获取树形列表数据，主要用于多级分类列表管理
    /// </summary>
    public class GetTreeListDataBLL<T>: GetListDataBLL<T>, IGetTreeListData<T> where T : MultipleLevelModelBase<T>, new()
    {

        public GetTreeListDataBLL(DataBaseContext dataBaseContext) : base(dataBaseContext)
        {
        }
        /// <summary>
        /// 树形数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<T> GetTreeList(NameValueCollection form)
        {
            TipsInfo tipsInfo = new TipsInfo();
            if (Executing != null)
            {
                tipsInfo = Executing.Invoke(); //执行前
            }
            if (tipsInfo.State == 0)
            {
                return new List<T>();
            }
            base.initListConfig(form,null);
            DbSet<T> dbset = _DbContext.DbSet<T>();
            var list = dbset.Query(QueryCondition, OrderBy, null, QueryDbParameters);
            foreach (var item in list)
            {
                IEnumerable<T> children = GetChildren(item.Id);
                if (children.Count() > 0){
                    item.hasChildren = true;
                    //item.children = children;
                }
                else{
                    item.hasChildren = false;
                    //item.children = null;
                }
                base.SetRelativeData(dbset, item, item.Id);
            }
            Executed?.Invoke(list);
            return list;
        }

        /// <summary>
        /// 检测是否包含子级
        /// </summary>
        /// <returns></returns>
        private IEnumerable<T> GetChildren(int id)
        {
            return _DbContext.DbSet<T>().Query("ParentId=@ParentId", OrderBy, null, new { ParentId = id });
        }

    }
}